<script type="text/javascript">
	
	$.fn.serializeObject = function() {
		var o = {};
		var a = $(this).serializeArray();
		for(var i = 0; i < a.length; i++){
			var name = a[i]['name'];
			var value = a[i]['value'];
			if(value == 'on') value = 1;
			if(value == 'off') value = 0;
			o[name] = value;
		}
		return o;
	}
	
	Order = {
		save: function() {
			var data = {};
			data.total = $('#total').val();
			data['items'] = [];
			var items = $('#productDg').datagrid('getRows');
			for(var i = 0; i < items.length; i++){
				items[i]['productType'] == 'Service';
				delete items[i].editing;
				data['items'].push(items[i]);
			}
			$.ajax({url: '/store/create', type: 'post', data: data, success: function(resp) {
				window.location = '/store';
			}});
		},
		back: function() {
			window.location = '/store';
		}
	};
	function addProductToOrder(evt) {
		if(evt.isCat == '0') {
			var items = $('#productDg').datagrid('getRows');
			var orderItem = false;
			var itemIndex = false;
			for(var i = 0; i < items.length; i++) {
				var item = items[i];
				if (item.productId == evt.id) {
					orderItem = item;
					itemIndex = i;
					break;
				}
			}
			if(!orderItem) {
				$('#productDg').datagrid('appendRow',{
					productId: evt.id,
					productName: evt.name,
					productType: 'Service',
					price: evt.price,
					quantity: 1,
					total: evt.price
				});
			} else {
				$('#productDg').datagrid('updateRow',{
					index: itemIndex,
					row: {
						productId: evt.id,
						productName: evt.name,
						price: evt.price,
						quantity: orderItem.quantity + 1,
						total: (orderItem.quantity + 1) * evt.price
					}
				});
			}
			calculateTotal();
		}
	}
	
	var gridEditing = {
		gridId : '',
		gridVar: '',
		formatAction: function(value,row,index){
			if (row.editing){
				var s = '<a href="#" onclick="'+this.field+'.saverow(this)">Lưu</a> ';
				var c = '<a href="#" onclick="'+this.field+'.cancelrow(this)">Hủy</a>';
				return s+c;
			} else {
				var e = '<a href="#" onclick="'+this.field+'.editrow(this)">Sửa</a> ';
				var d = '<a href="#" onclick="'+this.field+'.deleterow(this)">Xóa</a>';
				return e+d;
			}
		},
		init: function() {
			var that = this;
			$(function(){
				$(that.gridId).datagrid({
					onBeforeEdit:function(index,row){
						row.editing = true;
						that.updateActions(index,row);
					},
					onAfterEdit:function(index,row){
						row.editing = false;
						that.updateActions(index, row);
					},
					onCancelEdit:function(index,row){
						row.editing = false;
						that.updateActions(index,row);
					}
				});
			});
		},
		updateActions:function(index, row){
			$(this.gridId).datagrid('updateRow',{
				index:index,
				row:{}
			});
			calculateTotal();
		},
		getRowIndex: function (target){
			var tr = $(target).closest('tr.datagrid-row');
			return parseInt(tr.attr('datagrid-row-index'));
		},
		editrow: function (target){
			$(this.gridId).datagrid('beginEdit', this.getRowIndex(target));
			calculateTotal();
		},
		deleterow: function (target){
			var that = this;
			$.messager.confirm('Confirm','Bạn có muốn xóa?',function(r){
				if (r){
					$(that.gridId).datagrid('deleteRow', that.getRowIndex(target));
					calculateTotal();
				}
			});
		},
		saverow: function (target){
			$(this.gridId).datagrid('endEdit', this.getRowIndex(target));
			calculateTotal();
		},
		cancelrow: function (target){
			$(this.gridId).datagrid('cancelEdit', this.getRowIndex(target));
			calculateTotal();
		}
	};
	var productDg = $.extend({}, gridEditing, {gridId: '#productDg', gridVar: 'productDg',
		updateActions: function(index, row) {
			$(this.gridId).datagrid('updateRow',{
				index:index,
				row:{total: (row.price * row.quantity)}
			});
			calculateTotal();
		}
		
	});
	productDg.init();
	function calculateTotal() {
		var items = $('#productDg').datagrid('getRows');
		var total = 0;
		for(var i = 0; i < items.length; i++){
			total += parseFloat(items[i].total);
		}
		
		$('#totalSpan').html(total);
		$('#total').val(total);
	}
</script>
<table>
	<tr>
		<td style="width: 360px">
			<table id="productlist" title="Danh mục dịch vụ" class="easyui-treegrid" style="width:360px;height:300px"
					url="/tree/children?id=7"
					rownumbers="true" data-options="onDblClickRow:addProductToOrder"
					idField="id" treeField="name">
				<thead>
					<tr>
						<th field="name" width="150">Tên</th>
						<th field="price" width="80" align="right">Giá</th>
						<th field="quantity" width="80" align="right">Số lượng</th>
					</tr>
				</thead>
			</table>
		</td>
		<td style="width: 750px;">
			<table id="productDg" title="Dịch vụ đã đặt" style="width: 100%;"
				pagination="true" idField="id" rownumbers="true"
				fitColumns="true" singleSelect="true" nowrap="true" 
				data-options="border:false,fit:true">
				<thead>
					<tr>
						<th field="productName" width="120" sortable="true">Dịch vụ</th>
						<th field="price" editor="{type:'validatebox',options:{required:true}}" width="150">Giá</th>
						<th field="quantity" editor="{type:'validatebox',options:{required:true}}" width="70">Số lượng</th>
						<th field="total" width="120">Tổng cộng</th>
						<th field="id" data-options="hidden:true">Id</th>
						<th field="productId" data-options="hidden:true">Product Id</th>
						<th field="productType" data-options="hidden:true">Product Type</th>
						<th field="productDg" width="80" align="center" formatter="productDg.formatAction">Thao tác</th>
					</tr>
				</thead>
			</table>
		</td>
	</tr>
</table>
<table>
	<tr>
		<td>Tổng cộng</td>
		<td><span id="totalSpan"></span><input id="total" name="total" type="hidden" style="width: 150px" /></td>
	</tr>
</table>
<table>
	<tr>
		<td colspan="6">
			<a href="#" class="easyui-linkbutton"
		iconCls="icon-save" onclick="Order.save();">Lưu</a>
			<a href="#" class="easyui-linkbutton"
		iconCls="icon-back" onclick="Order.back();">Trở lại</a>
		</td>
	</tr>
</table>